﻿using Domain.Entity;
using DtoFw;
using DtoFw.Enum;
using DtoFw.Query;
using DtoFw.Result;
using Repository.Base;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
using Util;

namespace Repository
{
    public class CasePhysicalEvidenceTransfereRepository : BaseRepository<CasePhysicalEvidenceTransfereEntity>
    {
        private readonly SnowFlakeGenerator worker;
        public CasePhysicalEvidenceTransfereRepository(SnowFlakeGenerator snowFlakeGenerator) : base(snowFlakeGenerator)
        {
            this.worker = snowFlakeGenerator;
        }
        public long GetNext()
        {
            return worker.NextId();
        }

        private string GetTranLocByEviId(long eviID, long tranID, long? vType)
        {
            if (!vType.HasValue || vType != 7)
                return string.Empty;

            var vResult = base.GetDb().Queryable<CasePhysicalEvidenceTransfereEntity>()
                     .Where(v => v.EvidenceId == eviID && v.Id != tranID)
                     .OrderBy(v => v.Id, OrderByType.Desc).ToList();

            if (vResult.Count > 0)
                return vResult[0].Location;

            return string.Empty;
        }

        public BaseGenericResult<List<TransfereEvidenceRespDto>> GetTransfereEvidences(long TransfereId)
        {
            var baseEntity = base.GetDb().Queryable<CasePhysicalEvidenceTransfereEntity>()
                  .First(x => x.Id == TransfereId && !x.IsDeleted);
            if (baseEntity == null)
                return new BaseGenericResult<List<TransfereEvidenceRespDto>>();
            var list = base.GetDb().Queryable<CasePhysicalEvidenceTransfereEntity, CasePhysicalEvidenceEntity>((t1, t2) => new JoinQueryInfos(
                  JoinType.Left, t1.EvidenceId == t2.Id))
                 .Where((t1, t2) => t1.DeliveryNo == baseEntity.DeliveryNo && !t1.IsDeleted && !t2.IsDeleted)
                 .OrderBy((t1, t2) => t1.CreateTime, OrderByType.Desc)
                 .Select((t1, t2) => new TransfereEvidenceRespDto()
                 {
                     EviId = t2.Id,
                     TranId = t1.Id,
                     DeliveryDicType = t1.DeliveryDicType,
                     Describe = t2.Describe,
                     EvidenceName = t2.Name,
                     EvidenceNo = t2.No,
                     EvidenceQuntity = t2.Quantity,
                     EvidenceShape = t2.Shape,
                     TransfereNo = t1.DeliveryNo,
                     UsefulLife = t2.UsefulLife,
                     ExtractionDateTime = t2.ExtractionDateTime,
                     ExtractionParts = t2.ExtractionParts,
                     ExtractionPersonName = t2.ExtractionPersonName,
                     Source = t2.Source,
                     ExtractMethod = t2.ExtractMethod,
                     Location = t1.Location,
                     LocationId = t1.LocationId,
                     //BeforeLocation = GetTranLocByEviId(t2.Id, t1.Id, t1.DeliveryDicType),
                     CreateTime = t1.CreateTime,
                     Creator = t1.Creator,
                     DeliveryTime = t1.DeliveryTime,
                     ReturnTime = t1.ReturnTime,
                     Status = t1.EvidenceStatus,
                     ReceiverOrgan = t1.ReceiverOrgan,
                     Receiver = t1.Receiver,
                     ReceiverPhone = t1.ReceiverPhone,
                     Remark = t1.Remark,
                     Transferor = t1.Transferor,
                     TransferorOrgan = t1.TransferorOrgan,
                     TransferorPhone = t1.TransferorPhone,
                     
                 }).ToList();

            foreach (var item in list)
            {
                item.BeforeLocation = GetTranLocByEviId(item.EviId, item.TranId, item.DeliveryDicType);
                item.CabinetCode = GetCabinetCode(item.LocationId);
            }

            return BaseGenericResult<List<TransfereEvidenceRespDto>>.Succeed(list);
        }

        public HaiKangTransDto GetTransfereEvidences(string tranNo)
        {
            var list = base.GetDb().Queryable<CasePhysicalEvidenceTransfereEntity, CasePhysicalEvidenceEntity>((t1, t2) => new JoinQueryInfos(
                  JoinType.Left, t1.EvidenceId == t2.Id))
                 .Where((t1, t2) => (t1.DeliveryNo == tranNo || t2.No == tranNo) && !t1.IsDeleted && !t2.IsDeleted)
                 .OrderBy((t1, t2) => t1.CreateTime, OrderByType.Desc)
                 .Select((t1, t2) => new TransfereEvidenceRespDto()
                 {
                     CaseId = t2.CaseId,
                     EviId = t2.Id,
                     TranId = t1.Id,
                     DeliveryDicType = t1.DeliveryDicType,
                     DeliveryDicTypeName = t1.DeliveryDicTypeName,
                     Describe = t2.Describe,
                     EvidenceName = t2.Name,
                     EvidenceNo = t2.No,
                     EvidenceQuntity = t2.Quantity,
                     EvidenceShape = t2.Shape,
                     TransfereNo = t1.DeliveryNo,
                     UsefulLife = t2.UsefulLife,
                     ExtractionDateTime = t2.ExtractionDateTime,
                     ExtractionParts = t2.ExtractionParts,
                     ExtractionPersonName = t2.ExtractionPersonName,
                     Source = t2.Source,
                     ExtractMethod = t2.ExtractMethod,
                     Location = t1.Location,
                     //BeforeLocation = GetTranLocByEviId(t2.Id, t1.Id, t1.DeliveryDicType),
                     CreateTime = t1.CreateTime,
                     Creator = t1.Creator,
                     DeliveryTime = t1.DeliveryTime,
                     ReturnTime = t1.ReturnTime,
                     Status = t1.EvidenceStatus,
                     ReceiverOrgan = t1.ReceiverOrgan,
                     Receiver = t1.Receiver,
                     ReceiverPhone = t1.ReceiverPhone,
                     Remark = t1.Remark,
                     Transferor = t1.Transferor,
                     TransferorOrgan = t1.TransferorOrgan,
                     TransferorPhone = t1.TransferorPhone
                 }).ToList();

            HaiKangTransDto dto = new HaiKangTransDto();
            HaiKangData hData = new HaiKangData();
            HaiKangCaseinfo hCaseInfo = new HaiKangCaseinfo();
            List<HaiKangEvidencelist> hList = new List<HaiKangEvidencelist>();

            dto.data = hData;

            if (list.Count == 0)
                return dto;

            var _tInfo = list[0];

            hData.vType = 3;
            if (_tInfo.DeliveryDicType == 7)
                hData.vType = 2;
            if (_tInfo.DeliveryDicType == 8)
                hData.vType = 1;

            hData.outReason = _tInfo.DeliveryDicTypeName;
            hData.caseInfo = hCaseInfo;
            hData.evidenceList = hList;
            var caseInfo = base.GetDb().Queryable<CaseEntity>().First(v => v.Id == _tInfo.CaseId);
            if (caseInfo != null)
            {
                hCaseInfo.caseName = caseInfo.CaseName;
                hCaseInfo.caseNo = caseInfo.CaseNo;
                hCaseInfo.caseTime = caseInfo.CaseTime.HasValue ? caseInfo.CaseTime.Value.ToString("yyyy-MM-dd") : "";
                hCaseInfo.caseAddress = caseInfo.CasePlace;
            }

            foreach (var item in list)
            {
                string[] locs;
                if (item.DeliveryDicType == 7) //更换位置
                {
                    var cLoc = GetTranLocByEviId(item.EviId, item.TranId, item.DeliveryDicType);
                    locs = cLoc.Split("-");
                    hList.Add(new HaiKangEvidencelist
                    {
                        evidenceName = item.EvidenceName,
                        evidenceNo = item.EvidenceNo,
                        evidenceNumber = item.EvidenceQuntity.HasValue ? item.EvidenceQuntity.ToString() : "1",
                        cellCode = locs.Length >= 3 ? locs[2] : "0",
                        cellName = locs.Length >= 2 ? locs[1] : "0",
                        cabinetNo = locs.Length >= 1 ? locs[0] : "0",
                        Location = cLoc,
                    });
                }

                locs = item.Location.Split("-");
                hList.Add(new HaiKangEvidencelist
                {
                    evidenceName = item.EvidenceName,
                    evidenceNo = item.EvidenceNo,
                    evidenceNumber = item.EvidenceQuntity.HasValue ? item.EvidenceQuntity.ToString() : "1",
                    cellCode = locs.Length >= 3 ? locs[2] : "0",
                    cellName = locs.Length >= 2 ? locs[1] : "0",
                    cabinetNo = locs.Length >= 1 ? locs[0] : "0",
                    Location = item.Location,
                });
            }

            dto.total = hList.Count;

            return dto;
        }
        /// <summary>
        /// 查询柜子类型
        /// </summary>
        public string GetCabinetCode(long? locationId)
        {
            if (locationId == null || locationId.Value < 0)
            {
                return null;
            }
            string sql = $@" SELECT `CabinetCode` FROM room_cabinet where `Id` in(SELECT `CabinetId` FROM room_box where `Id`={locationId}) ";

            return Convert.ToString(this.GetDb().Ado.GetScalar(sql));
        }

        public List<UserList> GetBoxUserList(string corpCode, string deviceCode, string startTime, string endTime, string orderby, int pageNum, int pageSize)
        {
            if (pageNum == 0) pageNum = 1;
            string sql = $" SELECT * FROM boxuserlist where modifyTime>='{startTime}' and modifyTime<='{endTime}' LIMIT {(pageNum-1) * pageSize},{pageSize}";

            return this.GetDb().Ado.SqlQuery<UserList>(sql);
        }

        public int GetBoxUserListCount( string startTime, string endTime)
        {
            string sql = $" SELECT count(1) FROM boxuserlist where modifyTime>='{startTime}' and modifyTime<='{endTime}'";

            return Convert.ToInt16(this.GetDb().Ado.GetScalar(sql));
        }


        /// <summary>
        /// 物品流转记录
        /// </summary>
        /// <param name="reqDto"></param>
        /// <returns></returns>
        public Pager<EvidenceTransferePagerRespDto> QueryEvidenceTransferePager(EvidenceTransfereQueryReqDto reqDto)
        {
            int total = 0;
            Pager<EvidenceTransferePagerRespDto> pager = new Pager<EvidenceTransferePagerRespDto>();
            pager.Data = base.GetDb().Queryable<CasePhysicalEvidenceTransfereEntity, CasePhysicalEvidenceEntity>((t1, t2) => new JoinQueryInfos(
                JoinType.Left, t1.EvidenceId == t2.Id))
                .Where((t1, t2) => t1.EvidenceId == reqDto.EvidenceId && !t1.IsDeleted && !t2.IsDeleted)
                .OrderBy((t1, t2) => t1.CreateTime, OrderByType.Desc)
                .Select((t1, t2) => new EvidenceTransferePagerRespDto()
                {
                    DeliveryNo = t1.DeliveryNo,
                    DeliveryTime = t1.DeliveryTime,
                    Transferor = t1.Transferor,
                    TransferorPhone = t1.TransferorPhone,
                    Location = t1.Location,
                    Receiver = t1.Receiver,
                    Remark = t1.Remark,
                    EvidenceId = t1.EvidenceId,
                    DeliveryDicType = t1.DeliveryDicType,
                    DeliveryDicTypeName = t1.DeliveryDicTypeName,
                    Id = t1.Id,
                    Name = t2.Name,
                    No = t2.No,
                    Status = (EnumEvidenceStatus)t1.EvidenceStatus,
                    ReturnTime = t1.ReturnTime,
                    TransferorOrgan = t1.TransferorOrgan,
                    ReceiverOrgan = t1.ReceiverOrgan,
                    ReceiverPhone = t1.ReceiverPhone,
                    LocationTime = t1.LocationTime
                })
                .ToPageList(reqDto.Page, reqDto.PageSize, ref total); ;
            pager.TotalCount = total;
            return pager;
        }
    }
}
